<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        width: 100px;
        height: 100px;
        background: red;
        position: absolute;
        left: 0;
        top: 0;
      }
    </style>
  </head>
  <body>
    <div class="box"></div>
    <script>
      var boxEle = document.querySelector(".box");
      //   var timer = setInterval(function () {
      //     var num = parseInt(getComputedStyle(boxEle)["left"]);
      //     if (num == 300) {
      //       clearInterval(timer);
      //     } else {
      //       num += 10;
      //       boxEle.style.left = num + "px";
      //     }
      //   }, 100);
      function move(ele, target, dir, cb) {
        //       ele=boxEle ，target=移动的值，dir=移动的方向，cb=新建的函数
        var timer = setInterval(function () {
          var num = parseInt(getComputedStyle(ele)[dir]);
          // if(target<num){
          //     console.log("减值")
          //     var speed = -10
          // }else{
          //     var speed = 10
          // }
          var speed = target < num ? -10 : 10;
          if (num == target) {
            clearInterval(timer);
            console.log("停止了");
            // if (cb) {
            //   cb();
            // }
            cb && cb();
          } else {
            num += speed;
            ele.style[dir] = num + "px";
          }
        }, 1000);
      }
      move(boxEle, 300, "left", function () {
        console.log("传入的函数");
        move(boxEle, 300, "top", function () {
          move(boxEle, 0, "left", function () {
            move(boxEle, 0, "top");
            console.log("所有运动完成");
          });
        });
      });
    </script>
  </body>
</html>
